//
//  JNTHomeViewController.m
//  OA
//
//  Created by 王文晓 on 16/8/4.
//  Copyright © 2016年 王文晓. All rights reserved.
//

#import "JNTHomeViewController.h"
#import "SDCycleScrollView.h"
#import "ApplyViewController.h"
#import "OfficialDocumentViewController.h"
#import "CalendarViewController.h"
#import "JNTMoreViewController.h"



@interface JNTHomeViewController ()<SDCycleScrollViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout, PersonalNeedCollectionViewCellDelegate>
{
    NSIndexPath *_indexPath;
    BOOL _isDeletingStatus;
    UIButton *_sureBtn;
}

@property (nonatomic, strong) SDCycleScrollView *cycleScrollView; //滚动视图
@property (nonatomic, strong) UICollectionView *collectionView;   //分区一布局
@property (nonatomic, strong) NSMutableArray *imageArray;        //存储图片
@property (nonatomic, strong) NSMutableArray *titleArray;        //存储标题
@property (nonatomic ,assign) BOOL isdelete;
@property (nonatomic ,assign) NSInteger sectionCount;

@property (nonatomic, strong) NSMutableDictionary *parameter;   //参数字典


@property (nonatomic, retain) NSMutableArray *showKeyMArray;    // 存取的只是key(int型的)

@end

@implementation JNTHomeViewController
 
- (NSMutableArray *)showKeyMArray {
    if (!_showKeyMArray) {
        _showKeyMArray = [NSMutableArray array];
    }
    return _showKeyMArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpNavgationBar];
    [self.view addSubview:self.cycleScrollView];
    [self.view addSubview:self.collectionView];
  
    
    [self.showKeyMArray addObjectsFromArray:@[@0, @1, @3, @9, @10]];
    // 添加长按手势
    UILongPressGestureRecognizer *longPressGR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];
    longPressGR.minimumPressDuration = 1.0;
    [self.collectionView addGestureRecognizer:longPressGR];
    
  
    // 添加完成按钮
    _sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _sureBtn.backgroundColor = [UIColor grayColor];
    _sureBtn.frame = CGRectMake(3, 210+3, kScreenWidth-6, 30);
    [_sureBtn setTitle:@"完成" forState:UIControlStateNormal];
    [_sureBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_sureBtn addTarget:self action:@selector(sureAction) forControlEvents:UIControlEventTouchUpInside];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_isDeletingStatus) { // 视图将要消失的时候，如果是删除状态，则取消删除状态
        [self sureAction];
    }
}

- (void)sureAction {
//    NSLog(@"完成");
    _isDeletingStatus = NO;
    [self.collectionView reloadData];
}

// 长按手势的点击方法
-(void)longPressToDo:(UILongPressGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateBegan) {

        _isDeletingStatus = YES;
        [self.collectionView reloadData];

    }
}
- (void)deleteKeyWithIndexPath:(NSIndexPath *)indexPath {
    [self.showKeyMArray removeObjectAtIndex:indexPath.item];
    [self.collectionView reloadData];
}


#pragma Mark - -------UICollectionView的代理方法------

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.showKeyMArray.count == self.dataSourceMArr.count) {
        return self.showKeyMArray.count;
    }
     return self.showKeyMArray.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    PersonalNeedCollectionViewCell *CELL = [collectionView dequeueReusableCellWithReuseIdentifier:@"PersonalNeedCell" forIndexPath:indexPath];
    CELL.delegate = self;
    CELL.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
    
    
    CELL.pointView.alpha = 0;   // 默认隐藏 删除按钮
    CELL.cellLabel.text = nil;
    CELL.cellImageView.image = nil;
    
    
    if (_isDeletingStatus) {    // 如果是 删除状态，显示 删除 按钮
        if (indexPath.item != self.showKeyMArray.count) {
            CELL.pointView.alpha = 1;
            
            // 添加抖动效果
            CALayer*viewLayer=[CELL layer];
            CABasicAnimation*animation=[CABasicAnimation
                                        
                                        animationWithKeyPath:@"transform"];
            animation.duration=0.1;
            animation.repeatCount = 100000;
            animation.autoreverses=YES;
            animation.fromValue=[NSValue valueWithCATransform3D:CATransform3DRotate
                                 
                                 (viewLayer.transform, -0.03, 0.0, 0.0, 0.03)];
            animation.toValue=[NSValue valueWithCATransform3D:CATransform3DRotate
                               
                               (viewLayer.transform, 0.03, 0.0, 0.0, 0.03)];
            [viewLayer addAnimation:animation forKey:@"wiggle"];
        }
    }
    
    if (indexPath.row == self.showKeyMArray.count) {
        CELL.cellLabel.text = @"更多";
        CELL.cellImageView.image = [UIImage imageNamed:@"ic_add"];
    } else {
        CELL.cellLabel.text = [self getShowTitleArray][indexPath.item];
        NSNumber *index = self.showKeyMArray[indexPath.item];
        homeModel *model = self.dataSourceMArr[[index intValue]];
        CELL.cellImageView.image = [UIImage imageNamed:[self getImgNamesWithID:[NSString stringWithFormat:@"%@", model.ID]]];
    }
   
    return CELL;
}




//注册头分区
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        if (indexPath.section == 0) {
            
            [headerView addSubview:self.cycleScrollView];
            
            [headerView addSubview:_sureBtn];
            if (_isDeletingStatus) {
                _sureBtn.alpha = 1;
            } else {
                _sureBtn.alpha = 0;
            }
        }
        
        return headerView;
    } else if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        
        return nil;
    }
    return nil;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
   
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    
    return 0;

}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
        
        return UIEdgeInsetsMake(0, 0, 1, 1);
   
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
         return CGSizeMake((kScreenWidth-2)/4, kScreenWidth/4);
    }
    else if (indexPath.section == 1){
        
        return CGSizeMake(80, 80);
    
    }
    return CGSizeMake(0, 0);
}
//头分区的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        if (_isDeletingStatus) {
            return CGSizeMake(kScreenWidth, 210+36);
        }
        return CGSizeMake(kScreenWidth, 210);
        
    }else{
        return CGSizeMake(0, 0);
    }
}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_isDeletingStatus) {    // 如果是删除情况，不让点击item
        return;
    }
    
    if (indexPath.item == self.showKeyMArray.count) { // 更多的点击方法
        JNTMoreViewController *more = [[JNTMoreViewController alloc] init];
        more.dataSourceMArr = self.dataSourceMArr;
        more.showKeyMArray = [[self getNextPageShowTitleKeyArray] mutableCopy];
        more.block = ^(int addKey) {    // 接受长按 的block回调
            [self.showKeyMArray addObject:[NSNumber numberWithInt:addKey]];
            [self.collectionView reloadData];
        };
        [self.navigationController pushViewController:more animated:YES];
    } else {
//        获取当前点击item的下标
        NSNumber *index = self.showKeyMArray[indexPath.item];
//        从model中取出相对应的值
        homeModel *model = self.dataSourceMArr[[index intValue]];
//        跳转到相对应的VC中
        UIViewController *vc = [NSClassFromString([self getClassNamesWithID:[NSString stringWithFormat:@"%@", model.ID]]) new];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:NO];
    }
    
}


#pragma mark --滚动视图点击方法--
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    
    JNTLog(@"%ld",index);
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - SDCycleScrollView

- (SDCycleScrollView *)cycleScrollView{
    NSMutableArray *myArray = [NSMutableArray arrayWithObjects:[UIImage imageNamed:@"1.jpeg"],[UIImage imageNamed:@"2.jpeg"],[UIImage imageNamed:@"3.jpeg"], nil];
       if (!_cycleScrollView) {
        _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:kRect(0, 0, kScreenWidth,210) imageNamesGroup:myArray];
        _cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        _cycleScrollView.autoScroll = YES;
           _cycleScrollView.delegate = self;
        _cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;

    }
    return _cycleScrollView;
}


#pragma mark - 设置导航条
- (void)setUpNavgationBar
{
    self.navigationController.navigationBar.translucent = NO;
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"上栏"] forBarMetrics:UIBarMetricsDefault];
    self.navigationItem.title = @"通号移动云平台";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"退出" style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
}

//退出该应用
- (void)rightBtnClick
{
    exit(0);
    
}


//九宫格布局
- (UICollectionView *)collectionView {
    
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-124) collectionViewLayout:flowLayout];
        [_collectionView registerNib:[UINib nibWithNibName:@"PersonalNeedCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"PersonalNeedCell"];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
    }
    return _collectionView;
}

- (NSMutableArray *)dataSourceMArr{
    
    if (!_dataSourceMArr) {
        
        _dataSourceMArr = [NSMutableArray array];
    }
    return _dataSourceMArr;
}






// 这里根据 返回 数据里面的ID 来判断显示哪个VC，根据判断需求修改(这里到时候把要跳转的VC名称 对应写好)
- (NSString *)getClassNamesWithID:(NSString *)classID {
    NSDictionary *classNames = @{@"33":@"OneCartoonViewController",
                                 @"34":@"OfficialDocumentViewController",
                                 @"35":@"UserCenterViewController",
                                 @"36":@"SignInViewController",
                                 @"37":@"ApplyViewController",
                                 @"38":@"ApplyViewController",
                                 @"39":@"CalendarViewController",
                                 @"40":@"ApplyViewController",
                                 @"41":@"ApplyViewController",
                                 @"42":@"UserCenterViewController",
                                 @"47":@"ApplyViewController",
                                 @"48":@"EntranceGuardViewController",
                                 @"81":@"ApplyViewController",
                                 @"88":@"ApplyViewController",
                                 @"89":@"ApplyViewController",
                                 @"100":@"OneCartoonViewController"};
    
   
    return [classNames objectForKey:classID];
}

// 根据 数据里面的ID 获取本地图片名称
- (NSString *)getImgNamesWithID:(NSString *)classID {
    NSDictionary *imgNames = @{@"33":@"home_btn_approve_f",
                                 @"34":@"home_btn_workbench_f",
                                 @"35":@"home_btn_news_f",
                                 @"36":@"home_btn_signin_f",
                                 @"37":@"home_btn_visitor_f",
                                 @"38":@"home_btn_package_f",
                                 @"39":@"home_btn_schedule_f",
                                 @"40":@"home_btn_report_f",
                                 @"41":@"home_btn_parking_f",
                                 @"42":@"home_btn_personal_f",
                                 @"47":@"",  // 这个图片没找到
                                 @"48":@"",  // 这个图片没找到
                                 @"81":@"home_btn_news_approval_f",
                                 @"88":@"ic_meetingroom",
                                 @"89":@"ic_meetingroom_check",
                                 @"100":@"home_btn_video_f"};
    
    
    return [imgNames objectForKey:classID];
}









// 获取当前需要展示的title
- (NSArray *)getShowTitleArray {
    
    
    NSMutableArray *titleArray = [NSMutableArray array];
    for (int i = 0; i < self.showKeyMArray.count; i++) {
        NSNumber *index = self.showKeyMArray[i];
        homeModel *model = self.dataSourceMArr[[index intValue]];
        [titleArray addObject:model.name];
    }
    return titleArray;
}

// 获取下个界面 需要展示的title(所有数据 - 本页面展示的数据)
- (NSArray *)getNextPageShowTitleKeyArray {
    
    NSMutableArray *nextPageKeyArray = [NSMutableArray array];

    for (int i = 0; i < self.dataSourceMArr.count; i++) {
        if (![self.showKeyMArray containsObject:[NSNumber numberWithInt:i]]) {
            [nextPageKeyArray addObject:[NSNumber numberWithInt:i]];
        }
    }
    return nextPageKeyArray;
}







@end
